package com.demon.net.json

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/EasyHttp
 * time   : 2020/05/05
 * desc   : double / Double 类型解析适配器，参考：[com.google.gson.internal.bind.TypeAdapters.DOUBLE]
 */
open class DoubleTypeAdapter : TypeAdapter<Number?>() {
    @Throws(IOException::class)
    override fun read(`in`: JsonReader): Number? {
        return when (`in`.peek()) {
            JsonToken.NUMBER -> `in`.nextDouble()
            JsonToken.STRING -> return try {
                `in`.nextString().toDouble()
            } catch (e: NumberFormatException) {
                // 如果是空字符串则会抛出这个异常
                0
            }
            JsonToken.NULL -> {
                `in`.nextNull()
                null
            }
            else -> {
                `in`.skipValue()
                0
            }
        }
    }

    @Throws(IOException::class)
    override fun write(out: JsonWriter, value: Number?) {
        out.value(value)
    }
}